<?php

abstract class Soul_Db_Sql_Where extends Soul_Db_Sql_Base{

	protected $where = array(); 
    
	public function resetWhere(){
		$this->where = array();
		return $this;
	}    
    
	public function condition($field, $value, $flag = 'eq', $paramType = 's', $or = FALSE){
		$field = $this->addQualifier($field);
		$paramName = 'p'.count($this->parameters);
		$paramType = ':'.$paramType;
		switch(strtolower($flag)){
			case 'eq':
				return $this->where($field.'=:'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value);
			case 'gt':
				return $this->where($field.'>:'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value);
			case 'lt':
				return $this->where($field.'<:'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value);
			case 'gteq':
				return $this->where($field.'>=:'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value);
			case 'lteq':
				return $this->where($field.'<=:'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value);
			case 'neq':
				return $this->where($field.'!=:'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value);
			case 'like':
				return $this->where($field.' LIKE :'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value);
			case 'in':
				return $this->where($field.' IN(:'.$paramName.':a)', $or)
					 		->addParameter($paramName, $value);
			case 'notin':
				return $this->where($field.' NOT IN(:'.$paramName.':a)', $or)
					 		->addParameter($paramName, $value);
			case 'starts':
				return $this->where($field.' LIKE :'.$paramName.$paramType, $or)
					 		->addParameter($paramName, $value.'%');
			case 'ends':
				return $this->where($field.' LIKE :'.$paramName.$paramType, $or)
					 		->addParameter($paramName, '%'.$value);
			case 'contains':
				return $this->where($field.' LIKE :'.$paramName.$paramType, $or)
					 		->addParameter($paramName, '%'.$value.'%');
			case 'isnull':
				return $this->where($this->addQualifier($field).' IS NULL', $or);
			case 'notnull':
                return $this->where($this->addQualifier($field).' IS NOT NULL', $or);
		}
		return $this;
	}
	
	public function where($condition, $or = FALSE){
		if(count($this->where) > 0){
			$this->where[] = $or? 'OR': 'AND';
		}
		$this->where[] = $condition;
		return $this;
	}    
    
    public function toSql(){
		if(count($this->where) > 0){
			return ' WHERE '.implode(' ', $this->where);
		}        
        return '';
    }
}